<template>
  <el-dialog
    v-model="visible"
    title="用户属性管理"
    width="600px"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="attributes-management">
      <!-- 添加新属性 -->
      <el-card shadow="never" class="add-section">
        <template #header>
          <h4>添加新属性</h4>
        </template>
        
        <el-form ref="addFormRef" :model="addForm" :rules="addRules" inline>
          <el-form-item prop="key">
            <el-input
              v-model="addForm.key"
              placeholder="属性名称"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item prop="value">
            <el-input
              v-model="addForm.value"
              placeholder="属性值"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">添加</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 现有属性列表 -->
      <el-card shadow="never" class="list-section">
        <template #header>
          <div class="list-header">
            <h4>现有属性 ({{ Object.keys(attributes).length }} 个)</h4>
            <el-button type="success" size="small" @click="handleSaveAll">
              <el-icon><check /></el-icon>
              保存所有修改
            </el-button>
          </div>
        </template>

        <div v-if="Object.keys(attributes).length > 0" class="attributes-list">
          <div
            v-for="(value, key) in attributes"
            :key="key"
            class="attribute-item"
          >
            <div class="attribute-info">
              <div class="attribute-key">{{ key }}</div>
              <el-input
                v-model="attributes[key]"
                placeholder="属性值"
                size="small"
                @change="markAsModified(key)"
              />
            </div>
            <div class="attribute-actions">
              <el-tag v-if="modifiedKeys.includes(key)" type="warning" size="small">
                已修改
              </el-tag>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(key)"
              >
                <el-icon><delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无自定义属性" :image-size="80" />
      </el-card>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSaveAll" :loading="saving">
          保存所有修改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserDetail, getUserAttributes, updateUserAttributes, deleteUserAttribute } from '@/api/user'

export default {
  name: 'UserAttributesDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'updated'],
  setup(props, { emit }) {
    const visible = ref(props.modelValue)
    const loading = ref(false)
    const saving = ref(false)
    const addFormRef = ref(null)
    
    const attributes = ref({})
    const modifiedKeys = ref([])

    // 添加属性表单
    const addForm = reactive({
      key: '',
      value: ''
    })

    // 添加属性验证规则
    const addRules = {
      key: [
        { required: true, message: '请输入属性名称', trigger: 'blur' },
        { min: 1, max: 50, message: '属性名称长度在 1 到 50 个字符', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (attributes.value[value]) {
              callback(new Error('属性名称已存在'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      value: [
        { required: true, message: '请输入属性值', trigger: 'blur' },
        { max: 500, message: '属性值不能超过 500 个字符', trigger: 'blur' }
      ]
    }

    // 监听对话框显示状态
    watch(() => props.modelValue, (val) => {
      visible.value = val
      if (val && props.user?.id) {
        fetchUserAttributes()
      }
    })

    watch(visible, (val) => {
      emit('update:modelValue', val)
    })

    // 获取用户属性
    const fetchUserAttributes = async () => {
      loading.value = true
      try {
        const response = await getUserDetail(props.user.id)
        attributes.value = { ...response.data.attributes }
        modifiedKeys.value = []
      } catch (error) {
        ElMessage.error('获取用户属性失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 标记为已修改
    const markAsModified = (key) => {
      if (!modifiedKeys.value.includes(key)) {
        modifiedKeys.value.push(key)
      }
    }

    // 添加属性
    const handleAdd = async () => {
      try {
        await addFormRef.value.validate()
      } catch (error) {
        return
      }

      try {
        await updateUserAttributes(props.user.id, {
          [addForm.key]: addForm.value
        })

        attributes.value[addForm.key] = addForm.value
        
        // 重置表单
        addForm.key = ''
        addForm.value = ''
        addFormRef.value.resetFields()
        
        ElMessage.success('属性添加成功')
        emit('updated')
      } catch (error) {
        ElMessage.error('添加属性失败：' + error.message)
      }
    }

    // 删除属性
    const handleDelete = async (key) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除属性 "${key}" 吗？`,
          '删除属性',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await deleteUserAttribute(props.user.id, key)
        
        delete attributes.value[key]
        modifiedKeys.value = modifiedKeys.value.filter(k => k !== key)
        
        ElMessage.success('属性删除成功')
        emit('updated')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除属性失败：' + error.message)
        }
      }
    }

    // 保存所有修改
    const handleSaveAll = async () => {
      if (modifiedKeys.value.length === 0) {
        ElMessage.info('没有修改需要保存')
        return
      }

      saving.value = true
      try {
        // 构建更新数据
        const updateData = {}
        modifiedKeys.value.forEach(key => {
          updateData[key] = attributes.value[key]
        })

        await updateUserAttributes(props.user.id, updateData)
        
        modifiedKeys.value = []
        ElMessage.success('所有修改保存成功')
        emit('updated')
      } catch (error) {
        ElMessage.error('保存修改失败：' + error.message)
      } finally {
        saving.value = false
      }
    }

    // 关闭对话框
    const handleClose = () => {
      if (modifiedKeys.value.length > 0) {
        ElMessageBox.confirm(
          '有未保存的修改，确定要关闭吗？',
          '确认关闭',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          visible.value = false
          modifiedKeys.value = []
        }).catch(() => {
          // 用户取消，不执行任何操作
        })
      } else {
        visible.value = false
      }
    }

    return {
      visible,
      loading,
      saving,
      addFormRef,
      attributes,
      modifiedKeys,
      addForm,
      addRules,
      markAsModified,
      handleAdd,
      handleDelete,
      handleSaveAll,
      handleClose
    }
  }
}
</script>

<style scoped>
.attributes-management {
  max-height: 600px;
  overflow-y: auto;
}

.add-section {
  margin-bottom: 20px;
}

.add-section h4 {
  margin: 0;
  color: #303133;
}

.list-section h4 {
  margin: 0;
  color: #303133;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.attributes-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attribute-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fafafa;
}

.attribute-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 15px;
}

.attribute-key {
  font-weight: 500;
  color: #303133;
  min-width: 120px;
  padding: 8px 12px;
  background-color: #e9ecef;
  border-radius: 4px;
  text-align: center;
}

.attribute-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 